import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  WsResponse,
} from "@nestjs/websockets";

@WebSocketGateway({
  cors: {
    origin: "*",
  },
})
export class WebsocketsGateway
  implements OnGatewayConnection, OnGatewayDisconnect
{
  // 断开后
  handleDisconnect(client: WebSocket) {
    console.log("handleDisconnect", client);
  }

  // 存储客户端socket连接
  private clients = new Map<string, any>();

  // 设置最大容量
  private MAX_CAPACITY = 1000;

  private KICK_COUNT = 100; // 需要踢掉的键值对数量

  // 链接上
  handleConnection(client: WebSocket, ...args: any[]) {
    console.log("handleConnection", client); // sender
    const userId = Math.random().toString(36).substring(2, 9); // 示例ID生成方式
    // 检查当前 Map 的大小
    if (this.clients.size >= this.MAX_CAPACITY) {
      // 如果达到最大容量，删除最前面的 KICK_COUNT 个键值对
      console.log("Map 已满，正在删除最前面的键值对...");
      for (let i = 0; i < this.KICK_COUNT; i++) {
        this.clients.delete(this.clients.keys().next().value);
      }
    }
    this.clients.set(userId, client);
    const send_json = { type: "socket_connection", socketID: userId };
    client.send(JSON.stringify(send_json)); // 将用户ID发送回客户端
  }

  // 群发广播
  @SubscribeMessage("message")
  handleMessage(@MessageBody() data: string) {
    console.log("handleMessage", data);
    return "Hello from server";
  }

  // 特定用户广播
  @SubscribeMessage("messageToUserID")
  handleToUserID(@MessageBody() data: { receiverId: string; message: string }) {
    const { receiverId, message } = data;
    console.log("handleToUserID", receiverId, message);
    const client = this.clients.get(receiverId);
    if (client) {
      client.send(message);
    }
  }
}
// 特定用户广播
// {
//     "event": "messageToUserID",
//     "data": {
//     "receiverId":"mvz6c6m",//接收者ID
//         "message":"内容"
// }
// }

// 群发广播
// {
//     "event": "message",
//     "data": "Hello Nestjs ws"
// }

//web端使用方法
// var socket = new WebSocket("ws://localhost:9420");
// //申请一个WebSocket对象，参数是服务端地址，同http协议使用http://开头一样，WebSocket协议的url使用ws://开头，另外安全的WebSocket协议使用wss://开头
// socket.on('connect', () => {
//     console.log('Connected to the server!');
// });
//
// socket.on('user_id', (userId) => {
//     console.log('My user ID:', userId);
//     // 现在你可以使用这个userId来发送消息给特定用户
// });
//
// socket.on('message', (msg) => {
//     console.log('Received message:', msg);
// });
//
// // 发送消息给特定用户
// function sendMessageToUser(userId, message) {
//     socket.emit('messageToClient', { receiverId: userId, message: message });
// }
